const app = getApp();
let deviceId = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pledge_price:0,
    price_list:[],
    gs_device_id:0,
      show:false,
    datetime:0,
    nums:0,
      ids:'',
    alldata:'',
    use_hours:0,
    seeDetails: true,
    order_id: 0,
    coupon_id: 0,   //优惠卷id
    order: {},
    store_label:[],
    clock_time:0,//时间戳
    lock_code:'',
    use_end_time:'',
    mac_code:'',
    room_password:'',
    constantly_price:0,
    constantly_hour:0,
    price:0,
    formattedTotalPrices:0,
    showModalStatus:false,   //弹出页面
    //定时器
    payinterval:null,
    interval:null,
    keyInfo: {}, // 钥匙数据
    lock_state:false,
    fw_status:true,
    deposit:0,
    money:0,
    // 续租
    TotalPrices:0,
    endTime: new Date().getTime() + 60 * 60 * 1000, // 预订结束时间，假设为一小时后
    countDownend: 20, // 倒计时文本
    isShow:false, // 初始化显示
    numes:0,
    value: "2023-10-25 15:11",
    totaltime:0,
    pay_type:2,//1余额2是微信
    // 新的续租
    selectTime:false,
    date_arr:[],
    times: {},
    nowstime:'',//现在的时间
    select_date:'',
    allChosedData: {},
    time: '12:01',
    selectTime: false,
    id:'',
    alltotals:0,//这个不知道是干嘛的
    select_start:'',
    select_end:'',
    end:'',
    retention:''//保留切换的时间

  },
// 上面的续租
    renewalOk(){
   this.setData({
    selectTime:true
   })
//    this.confirmtimehaderl()
//    this.getSelectedTimes()//这个不知道干嘛的

    },
    timeList(){
        
        var date_arr = [];
        for (var i = 0; i < 7; i++) {
            var now = new Date().getTime() + i * 86400000;
            date_arr.push(this.getDate(now));
        }
        this.setData({
            date_arr: date_arr,
            date:date_arr[0].date

        })
    },
    getDate: function (now) {
        var date = new Date(now),
            y = date.getFullYear(),
            m = date.getMonth() + 1,
            w = date.getDay(),
            d = date.getDate(),
            weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        m = ('0' + m).slice(-2);
        d = ('0' + d).slice(-2);
        return {
            week: weeks[w],
            date: y + '-' + m + '-' + d,
            name: m + '月' + d + '日'
        };

    },
    close_time: function (){
        this.setData({
            selectTime:false
           })
    },
//   下面不是续租的部分
  see_details: function () {
    var seeDetails = this.data.seeDetails
    seeDetails = !seeDetails
    this.setData({
      seeDetails: seeDetails
    })
  },
  code: function(){
    // wx.showModal({
    //     title: '开门',
    //     content: '确认开门吗？'})
    // wx.navigateTo({
    //   url: '/pages/pay_success/pay_success?order_id=' + this.data.order_id
    // })
  },


   // 续费 
   renew: function () {
    wx.navigateTo({
      url: '/pages/account_chongzhi/account_chongzhi'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
//   onLoad: function (options)
  onLoad: function (options) {
      
    var order_id = options.order_id || 0;
    this.data.order_id = order_id;
    this.Informationhader()
    this.timeList()
    this.data.deposit = wx.getStorageSync('deposit');
    this.data.money = wx.getStorageSync('money');
       this.setData({
        money:this.data.money,
        deposit:this.data.deposit,
        totaltime:this.data.value,
        ids:options.room_id || 0,
        select_date:this.data.date_arr[0].date 
                });

    //每10秒获取订单支付信息
    // this.payTiming();
     this.getSelectedTimes()
    // this.confirmtimehaderl()
  },
    formatTime(timestamp) {
    const date = new Date(timestamp * 1000); // 将秒数转换为毫秒数
  
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份从0开始，需要加1
    const day = ("0" + date.getDate()).slice(-2);
    const hours = ("0" + date.getHours()).slice(-2);
    const minutes = ("0" + date.getMinutes()).slice(-2);
      this.setData({
        start: `${year}-${month}-${day} ${hours}:${minutes}`

      })
  },
  
  Informationhader:function(){
    app.ajax({
        url: '/api/order/orderDetail',
        data: {
          order_id:this.data.order_id 
        },
        success: res => {
          if(res.code == 1){
              var datas = wx.getStorageSync('datas');
          this.datashader(res.data.end)
           this.formatTime(res.data.start);
            this.setData({
                alldata:`${this.data.start} 至 ${this.data.end}`,
              order_id:this.data.order_id ,
              order: res.data,
              store_label:res.data.label,
              price:res.data.price,
              total_price:res.data.total_price,
              use_hours:res.data.use_hours,
              clock_time:res.data.start,
              ids:res.data.room_id,
              datetime:res.datetime,
              gs_device_id:res.data.gs_device_id,
              price_list:res.data.price_list,
              pledge_price:res.data.pledge_price
            })
            wx.setStorageSync( 'gs_device_id',this.data.gs_device_id )
          }else{
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        }
      }, 1);


  },
//启动定时获取支付信息
payTiming:function(){
  this.payOrder(1,2);
//   this.payinterval = setInterval(function () {
//       this.payOrder(1,2);
//   }.bind(this), 5000);
},
/**
    * @param {*} pay_type           //支付方式 1余额 2微信
    * @param {*} operation_type     //1支付 2获取账单
    */
   payOrder:function(pay_type,operation_type){
    //console.log(this.data.pay_type)
     app.ajax({
          url: '/api/user/pay',
          data: {
            order_id: this.data.order_id,
            coupon_id: this.data.coupon_id,
            pay_type: pay_type,
            operation_type:operation_type
          },
          success: res => {
              if (res.code == 1) {
                  if(operation_type == 2){
                     var bill_money = res.data.bill_list[0].money;
                     var pay_price = bill_money - this.data.coupon_sub;
                     var vip_sub = 0;
                     if (this.data.rate > 0) {
                         vip_sub = pay_price * (10 - this.data.rate) / 10;
                         vip_sub = vip_sub.toFixed(2);
                         vip_sub = parseFloat(vip_sub);
                     }
                     pay_price = pay_price - vip_sub;
                     var coupon_info = this.data.coupon_sub + vip_sub;
                     this.data.constantly_hour = res.data.bill_data.hours;
                     this.data.constantly_price = res.data.bill_list[0].money;
                     this.setData({
                         bill_create_time: res.data.bill_data.create_time,
                         constantly_hour: this.data.constantly_hour,
                         constantly_price: this.data.constantly_price,
                       
                     });
                  }
              } else {
                //订单已经结束返回首页
                  if(res.data == 100){
                    wx.reLaunch({
                      url: '/pages/index/index'
                  })
                  clearInterval(this.payinterval);
                  }
                  wx.showToast({
                     title: res.msg,
                     icon: 'none'
                  })
              }
          }
     }, 1);
},

  
  getKeyInfo(lockId){
    wx.showModal({
        title: '开门',
        content: '确认开门吗？'})


    if(!lockId || lockId == ''){
      wx.showToast({
        title:`开锁失败，设备ID错误`,
        icon: 'none'
      });return
    }
    app.ajax({
      url: '/api/user/getkeyInfo',
      header: {
        id: this.data.order_id,
        // lockId:lockId
      },
      success: res => {
        if(res.code == 1){
          if(res.data.length === 0){
            wx.showToast({
              title:res.data.msg,
              icon: 'none'
            });return
          }
          this.setData({
            keyInfo: res.data,
           });
          // wx.setStorageSync('roompassword_orderid_'+res.data.id, res.data.data.password);
          // this.checkRoomPass()
        }else{
          wx.showToast({
            title: '获取失败',
            icon: 'none'
          })
        }
      }
    }, 1);
  },
  // 获取房间密码
  getRoomPass:function(){
    //   这里暂时不知道是干什么的，先稍等一下
    // if(this.data.order.lock_code =="" || this.data.order.lock_code==null){
    //   wx.showToast({
    //     title: "参数错误1",
    //     icon: 'none'
    //   })
    //   return
    // }
    // if(this.data.order.end =="" || this.data.order.end==null){
    //   wx.showToast({
    //     title: "参数错误2",
    //     icon: 'none'
    //   })
    //   return
    // }
    app.ajax({
      url: '/api/order/getRoomCode',
      data: {
        order_id:this.data.order_id
      },
      success: res => {
        if(res.code == 1){
        //   if(res.data.data.length === 0){
        //     wx.showToast({
        //       title:res.data.msg,
        //       icon: 'none'
        //     });return
        //   }
          this.setData({
            room_password: res.data.password,
           });
          wx.setStorageSync('roompassword_orderid_'+res.data.id, res.data.password);
          this.checkRoomPass()
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    }, 1);
  },
  //点击复制密码
  checkRoomPass: function () {
    var that = this;
    wx.showModal({
      title: '房间密码',
      content: that.data.room_password,
      showCancel: true,
      confirmText: '复制密码',
      success(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: that.data.room_password,
            success(res) {
              wx.getClipboardData({
                success(res) {
                  console.log(res.data) // data
                  wx.showToast({
                    title: "复制成功",
                    icon: 'none'
                  })
                },fail(res){
                  wx.showToast({
                    title: "复制失败",
                    icon: 'none'
                  })
                }
              })
            }
          })
        }
      }
    })
  },
    //倒计时函数
    countDown:function(){
      //倒计时
     // 1624550400
     var timestamp = Date.parse(new Date());  
     timestamp = timestamp / 1000;  
     console.log("当前时间戳为：" + timestamp);  
     if(this.data.clock_time<=0){
      return
    }
     console.log(this.data.clock_time)
     //var totalSecond = (Date.parse(new Date()) / 1000) - (Date.parse(this.data.clock_time) / 1000) + 2;
     var totalSecond = (Date.parse(new Date()) / 1000) - this.data.clock_time + 2;
     this.interval = setInterval(function () {
        // 秒数
        var second = totalSecond;
        // 天数位
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;
        // 小时位
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;
        // 分钟位
        var min = Math.floor((second - day * 3600 *24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;
        // 秒位
        var sec = second - day * 3600 * 24 - hr * 3600 - min*60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;
        this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
        });
        totalSecond++;
        if (totalSecond < 0) {
        clearInterval(this.interval);
        // wx.showToast({
        //   title: '未开始',
        // });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          fw_status:false
        });
        }
      }.bind(this), 1000);
 },
  getList: function(){

  },
  handleChange: function(e) {
    console.log(e)
    this.setData({
      value: e.detail.date
    })
    　var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
    　　const timestamp = date.getTime()+ Number(this.data.numes*3600000);
        this.sliderchange(timestamp)
},
setPayType: function (e) {
    var type = e.currentTarget.dataset.type;
    this.setData({
        pay_type: type
    })
},
account_chongzhi: function () {
    wx.navigateTo({
        url: '/pages/account_chongzhi/account_chongzhi',
    })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('我显示了');
        //倒计时延迟2秒才行
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      clearInterval(this.payinterval);
      clearInterval(this.interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      clearInterval(this.payinterval);
      clearInterval(this.interval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title: '加载中...'
    });
    // 模拟异步请求最新数据
    setTimeout(() => {
      // 在这里执行获取最新数据的逻辑，比如调用接口获取数据
      this.getSelectedTimes()
      // 数据获取完成后隐藏加载提示
      wx.hideLoading();
      // 停止当前页面下拉刷新
      wx.stopPullDownRefresh();
    }, 1000);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 结算
   */
  checkOutRoom:function(e){
    var room_id = e.target.dataset.room_id;
    // console.log(room_id,'room_id-------')
    // if(!room_id) {
    //   wx.showToast({
    //     title: '退房提交失败',
    //     icon: 'none'
    //   });
    //   return false;
    // }
    wx.showModal({
        title: '退房',
        content: '确认退房吗？',
        success (res) {
          if (res.confirm) {
            app.ajax({
                //   url: '/api/user/checkOutRoom',
                    url:'/api/order/cancell',
                  data: {
                    order_id: room_id
                  },
                  success: res => {
                    if(res.code == 1){
                        wx.navigateBack({
                            url:'/pages/my_order/my_order'
                        })
                    }
                    wx.showToast({
                      title: res.msg,
                      icon: 'none'
                    })
                  }
                }, 1);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },
  unsettled:function(e){
    var order_id = e.target.dataset.order_id;
    if(!order_id) {
      wx.showToast({
        title: '退房提交失败',
        icon: 'none'
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/unsettled/unsettled?order_id=' + orderorder_id
    })
  },
  goods:function(){
    wx.navigateTo({
      url: '/pages/book/book'
    })
  },
  closeRoomPower:function(e){
    var mac_code = e.target.dataset.mac_code;
    var mac_code = this.data.order.mac_code;
    console.log(mac_code)
    app.ajax({
        url: 'api/order/closeRoomPower',
        data: {
          order_id:this.data.order_id,
          mac_code:mac_code
        },
        success: res => {
          if(res.code == 2){
              wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  complete: function() {
                    wx.navigateTo({
                      url: '/pages/index/index'
                    })
                  }
                })
          }
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }, 1);

  },
  power:function(e){
    var mac_code = e.target.dataset.mac_code;
    var mac_code = this.data.order.mac_code;
    console.log(mac_code)
    if(!mac_code){
      wx.showToast({
        title: '通电失败',
        icon: 'none'
      });
      return false;
    }
    app.ajax({
      url: '/api/user/roomPowerOn',
      data: {
        order_id:this.data.order_id,
        mac_code:  mac_code,
        // is_source:1,//用户手动开电
      },
      success: res => {
        if(res.code == 2){
            wx.showToast({
                title: res.msg,
                icon: 'none',
                complete: function() {
                  wx.navigateTo({
                    url: '/pages/index/index'
                  })
                }
              })
        }
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, 1);
  },
  //开锁和闭锁
  room_lock:function(type){
    app.ajax({
      url: '/api/user/roomLockState',
      data: {
        id:  this.data.order.id,
        lockId:this.data.order.lockId,
      },
      success: res => {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, 1);
  },
  /**
   * 换房
   */
//   exchangeHouses:function(e){
//     var store_id = e.target.dataset.store_id,room_id = e.target.dataset.room_id;
//     console.log(store_id)
//     var list = '';
//     app.ajax({
//       url: '/api/index/getRoomList',
//       data: {
//         store_id: store_id,
//         room_id:room_id
//       },
//       success: res => {
//         if(res.code == 1){
//           list = res.data;
//         }
//         this.setData({
//           RoomList:list,
//           showModalStatus:true
//         });
//       }
//     })

//   },
// 续租
    btnOk:function(){
        this.setData({
            isShow: !this.data.isShow, // 切换显示状态
          });
   
    },
    slider3change:function(e){
        this.setData({
            TotalPrices:e.detail.value*this.data.price,
            numes: e.detail.value,
            formattedTotalPrices:(e.detail.value*this.data.price).toFixed(3)
        })
        console.log('点击了按钮',this.data.formattedTotalPrices)
    //     var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
    //     Largetime= Largetime.replace('ms','\t')
    // 　　var date = new Date(Largetime);
    // 　　var timestamp = date.getTime();
    //     timestamp=timestamp+e.detail.value*3600000

      　var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
    　　const timestamp = date.getTime()+ Number(e.detail.value*3600000);
        this.sliderchange(timestamp)
        console.log(e.detail.value,timestamp,'e---------')
    },
    sliderchange:function(e){
        var date = new Date(e); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) ;
        this.data.totaltime=Y + M + D + h + m 
        this.setData({
            totaltime: this.data.totaltime
        })
    },
    cancellation(){
        this.setData({
            isShow:false
          });
    },
    // getData(n){
    //  let   n=new Date(n)
    //     return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
    //   },
    determine(){
        // this.getData(Date.now())
        var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
       const timestamp = date.getTime()
        if(timestamp<Date.now()){
         return   wx.showToast({
                title: '选择的时间不能小于当前的时间',
                icon: 'none'
            });
        }
    },
  close:function(){
    this.setData({
      showModalStatus:false
    });
  },
  book:function(e) {
    wx.showModal({
      title: '',
      content: '是否确认换房，将会产生换房费用',
      success: (res) =>  {
       if (res.confirm) {
        var room_id = e.target.dataset.room_id;
        var order_id = e.target.dataset.order_id;
        if(!room_id && !order_id){
          wx.showToast({
            title: '参数错误',
            icon: 'none'
          })
        }
        app.ajax({
          url: '/api/user/exchangeHouses',
          data: {
            room_id: room_id,
            order_id: order_id
          },
          success: res => {
            if(res.code == 1){
              wx.showToast({
                title: res.msg,
                icon: 'none'
              });

              this.setData({
                showModalStatus:false
              });
              setTimeout(function(){
                  // wx.navigateBack({
                  //   delta: 1,
                  // })
                  // wx.navigateTo({
                  //   url: '/pages/opening_code/opening_code?order_id=' + order_id
                  // })
                  wx.redirectTo({
                    url: '/pages/opening_code/opening_code?order_id=' + order_id
                  })
              }, 3000);
            }else{
              wx.showToast({
                title: res.msg,
                icon: 'none'
            });

               if (res.code == 301) {

                //倒计时延迟2秒才行
                setTimeout(()=>{
                    wx.navigateTo({
                        url: '/pages/account_chongzhi/account_chongzhi'
                    })
                },1000)

                }
             
            }
          }
        })
       } else if (res.cancel) {
        console.log('用户点击取消')
        return false
       }
      }
     })
  },
     // 点击tab切换(下面的数据)----------
     swichNav: function (e,is) {
        // let _this = this
        // _this.data.date=e.currentTarget.dataset.date
        // this.getSelectedTimes()
        //  //接口调用
        // this.saveChosedTimes()
        // if(e.currentTarget.dataset.date!==this.data.nowstime){
        //     this.setData({
        //         selecttime: 0,
        //     })
        // }else if(e.currentTarget.dataset.date==this.data.nowstime){
        //  this.bindDatePackage()
        // }
        // // 下面
        // var date = e.currentTarget.dataset.date;
        // if (this.data.select_date == date) {
        //     return false;
        // } else {
        //     this.setData({
        //         select_date: date
        //     });
        //     this.slidertimes2();//更新
        // }
        let _this = this
        _this.data.date=e.currentTarget.dataset.date
          //接口调用
        this.getSelectedTimes()
        this.saveChosedTimes()
        
        if(e.currentTarget.dataset.date!==this.data.nowstime){
            this.setData({
                selecttime: 0,
            })
        }else if(e.currentTarget.dataset.date==this.data.nowstime){
         this.bindDatePackage()
        }
        // 下面
        var date = e.currentTarget.dataset.date;
        if (this.data.select_date == date) {
            return false;
        } else {
            this.setData({
                select_date: date
            });
            
            this.slidertimes2();//更新
           this.confirmtimehaderl()
    
        }
    },
    saveChosedTimes() {
      var chosedTimeIndexs = [] // 选中的时间列表下标
      var key = 'allChosedData.' + this.data.select_date // 获取切换前的选中日期，并生成对应的key
      this.data.times.forEach((t, idx) => {
        if (t.select) {
          chosedTimeIndexs.push(t)
        }
      })

      // 存储：记录切换前选中的数据到allChosedData
      var obj = {}
      obj[key] = chosedTimeIndexs
      this.setData(obj)
        //   更新数量
        this.Updatequantity()
    },
    saveChosedTimes() {
        var chosedTimeIndexs = [] // 选中的时间列表下标
        var key = 'allChosedData.' + this.data.select_date // 获取切换前的选中日期，并生成对应的key
        this.data.times.forEach((t, idx) => {
          if (t.select) {
            chosedTimeIndexs.push(t)
          }
        })
        // 存储：记录切换前选中的数据到allChosedData
        var obj = {}
        obj[key] = chosedTimeIndexs
        this.setData(obj)
        console.log(this.data.allChosedData)
          //   更新数量
          this.Updatequantity()
          
      },
      bindDatePackage(){
        var now = new Date();
        var hours = now.getHours()+':';
        var minutes = now.getMinutes();
        this.data.time= hours+minutes
            this.setData({
                selecttime: this.data.time,
                time: this.data.time
            })
    },
    slidertimes2:function(){
        var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
        Largetime= Largetime.replace('ms','\t')
        　var date = new Date(Largetime);
        　　var timestamp = date.getTime();
            timestamp=timestamp+this.data.numes*3600000
            this.sliderchange(timestamp)
    },
    getSelectedTimes: function () {
        
        var _this = this
        app.ajax({
          // url: '/api/index/roomTimes',
          url:'/api/user/getTimePeriod ',
          data: {
            // room_id: this.data.order_id,
           room_id: this.data.ids,
            // date: this.data.select_date,
            date:this.data.date,
            is_xu:1//是否续租
          },
          success: res => {
            if (res.code == 1) {
              let arr = res.data
             arr.forEach(function(item,index){
             if(item.flag==0){
              item.disabled=true
             }
            })
            //   debugger
              // chosedTime是选择后的日期, historyTimeIndexs是我们之前存储的选择后的时间下标
              let historyTimeIndexs = _this.data.allChosedData[_this.data.select_date] || []
              if (historyTimeIndexs.length > 0) {
                historyTimeIndexs.forEach(h => {
                  let idx = arr.findIndex(a => a.time === h.time)
                  if (idx > -1) {
                    arr[idx].select = true
                  }
                })
              }
              this.setData({
                times: arr
              })
              
            }
          }
        });
    },
    // 更新数量
    Updatequantity(){
        //   更新数量
            var allDatas=Object.values(this.data.allChosedData)
            var count = 0;
            for (let i = 0; i < allDatas.length; i++) {
            const innerArray = allDatas[i];
            for (let j = 0; j < innerArray.length; j++) {
                const item = innerArray[j];
                if (item.select === true) {
                count++;
       
                }
            }
     }
    
     let alltotalprices=Number(count*0.25)*Number(this.data.price)
     
     this.setData({
           nums:count*0.25,
           retention:count*0.25,
           formattedTotalPrices:alltotalprices.toFixed(3)
       })
        },
       // 开始
    selectTime: function (e) {
      var index = e.currentTarget.dataset.index;
      var times = this.data.times;
      if (times[index].flag === 0||times[index].flag === 2) {
        return; // 如果当前时间段不可选，则直接返回
      }
      if (times[index].select) {
        times[index].select = false; // 如果已经选中，则取消选中
        this.setData({
          nums:this.data.alltotals,
        })
        
      } else {
        times[index].select = true; // 如果未选中，则选中
        this.setData({
          nums:this.data.alltotals
        })
      }
      this.setData({
        times: times,
        nums:this.data.totalnums
      });
      console.log(this.data.nums,'nums-----2')
      this.updateSelection(); // 更新选中状态
    },
    updateSelection: function () {
      var times = this.data.times;
      var select_start = -1;
      var select_end = -1;
      var hasSelected = false;
      
      for (var i = 0; i < times.length; i++) {
       
        if (times[i].select) {
          if (!hasSelected) {
            select_start = i;
            hasSelected = true;
          }
          select_end = i;
        }
      }
      if (select_start !== -1 && select_end !== -1) {
        this.checkInterval(select_start, select_end); // 检查选中时间段是否有间隔选择

      }

    },
    checkInterval: function (start, end) {
    
      var times = this.data.times;
      for (var i = start + 1; i < end; i++) {
        if (times[i].flag ===0||times[i].flag== 2) {
            times[i].select=true
            // tiems[i].select=false
            console.log()
          wx.showToast({
            title: '不可以间隔选择',
            icon: 'none'
          });
          times[i].select = false; // 取消非法选中
          // times[15].select=false
          // 使用 slice() 方法截取索引为 13 到 19 的对象
        const slicedObjects = times.slice(start, end+1);
                slicedObjects.reverse(slicedObjects)
        // 打印截取后的对象
        let foundFlag0 = false;
        slicedObjects.forEach((object) => {
          if (object.flag === 0) {
            foundFlag0 = true;
          }
          
          if (foundFlag0) {
            object.select = false;
          }
        });
          console.log( times[i],slicedObjects,start,end,' times[i] times[i]')
          this.setData({
            nums:this.data.alltotals,
         
          })
        }else{
          // 这里使用间隔选择
        }
      }
      this.setData({
        times: times,
      });
      this.calculateTotal(); // 计算总时长
    },
    calculateTotal: function () {
      var times = this.data.times;
      var total = 0;
      for (var i = 0; i < times.length; i++) {
        if (times[i].select) {
          total += 0.25; // 假设每个时间段长度为0.5小时
        }
      }
     
            //   更新数量
        this.saveChosedTimes()
        // 判断对象中的key有多少个
        // let keys=this.data.allChosedData
        //  let alls=Object.values(keys)
      
    },
    // 下面
        confirm_time: function (){
            if(this.data.formattedTotalPrices==0){
                return    wx.showToast({
                    title: '总价不能小于0元',
                    icon: 'none'
                });
            }
        // 下面部分(这里不知道干嘛用的，我注释掉了)
        // var nums = this.data.nums;
        // console.log(this.data.room.start_dtime,nums,'this.data.room.start_dtime,nums-------')
        // if (nums < this.data.room.start_dtime) {
        //     wx.showToast({
        //         title: nums ? '预定时间'+this.data.room.start_dtime+'小时起' : '请选择预定时间',
        //         icon: 'none'
        //     });
        //     return false;
        // }
        // var room_id = this.data.id,
        //     date = this.data.select_date,
        //     timeslot = [],
        //     times = this.data.times,
        //     start = this.data.select_start,
        //     end = this.data.select_end;
        // for (var i in times) {
        //     if (times[i].select) {
        //         timeslot.push(times[i].time);
        //     }
        // }
        var _this=this
        wx.showModal({
        title: '提示',
        content: '确认支付'+_this.data.formattedTotalPrices +'元钱吗',
        success (res) {
          if (res.confirm) {
            _this.saveChosedTimes()
            _this.confirmtimehaderl()
            console.log(res.confirm,'res.confirm------')
            //   debugger
            app.ajax({
                url: 'api/order/extension',
                data: {
                    // pay_type    支付类型（1余额，2微信）
                    order_id:_this.data.order_id,   
                    // total_price:_this.data.TotalPrices,  
                    total_price:_this.data.formattedTotalPrices,  
                    start:_this.data.end, 		 
                    end:_this.data.totaltime,			
                    use_hours:_this.data.nums,   
                    time_periods:_this.data.allChosedData, 
                    price:_this.data.price,
                    pay_type:_this.data.pay_type,
                    is_xu:1
                },
                success: res => {
                if (res.code == 1) {
                    if(_this.data.pay_type&&_this.data.pay_type==1){
                        wx.navigateTo({
                            url: '/pages/my_order/my_order' 
                        })
                    }else{
             if (res.data &&_this.data.pay_type == 2) {
                wx.requestPayment({
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    paySign: res.data.paySign,
                    timeStamp: res.data.timeStamp,
                    signType: res.data.signType,
                    success: res => {
                        wx.navigateTo({
                            url: '/pages/my_order/my_order' 
                        })
                    }
                })
            } 
                    }
                }else if (res.code == 301) {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                    //倒计时延迟2秒才行
                    wx.navigateTo({
                        url: '/pages/account_chongzhi/account_chongzhi'
                    })
        
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            }
        }, 1);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    

   

        },
         // 选择最大的日期和最小的日期选择出来
    confirmtimehaderl(){
        const dates = Object.keys(this.data.allChosedData).filter(key => this.data.allChosedData[key].length > 0);
        const sortedDates = dates.sort();
       
        const minDate = sortedDates[0];
        console.log(minDate,'sortedDates---')
        const maxDate = sortedDates[sortedDates.length - 1];
        // 解决报错
        if(this.data.allChosedData[minDate]===undefined)   return
        const minDateData = (this.data.allChosedData[minDate][0]).time.split('-')[0];
        console.log(minDateData,'sortedDates---3')
        const length=(this.data.allChosedData[maxDate]).length-1
        const maxDateData = (this.data.allChosedData[maxDate])[length].time.split('-')[1]
        const combinedString = `${maxDate} ${maxDateData}`;
        console.log(combinedString,'combinedString--------')
        // // 原始数据
        // const dateStr = this.data.date_arr[0].name;
        // // 使用正则表达式提取月份和日期
        // const regex = /(\d{1,2})月(\d{1,2})日/;
        // const match = regex.exec(dateStr);
        // const month = match[1];
        // const day = match[2];
        // const currentYear = new Date().getFullYear();
        // // 构建新的日期字符串
        // const newDateStr = `${currentYear}-${month}-${day}`;
        // console.log(newDateStr); // 输出：2023-11-30
        this.setData({
            // date:newDateStr,
            // select_date:minDate,
            totaltime:combinedString,//最后一个时间
            time:minDateData,
        })
    },
    datashader(item){
        const timestamp = item; // 要转换的时间戳
        const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒级别的日期对象
        const year = date.getFullYear(); // 获取年份
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 获取月份，并补零
        const day = date.getDate().toString().padStart(2, '0'); // 获取日期，并补零
        const hour = date.getHours().toString().padStart(2, '0'); // 获取小时，并补零
        const minute = date.getMinutes().toString().padStart(2, '0'); // 获取分钟，并补零
        const formattedDateTime = `${year}-${month}-${day} ${hour}:${minute}`; // 格式化日期时间
        console.log(formattedDateTime); // 输出格式化后的日期时间字符串
        this.setData(
            {
                end:formattedDateTime
            }
        )
    },
    calserhaser:function(){
        this.setData({
            show:true
        })
    },
    getRoomhader:function(){
        this.setData({
            show:false
        })

    },
    shangpinglist:function(){
        wx.navigateTo({
          url: '/pages/scancode/scancode?gs_device_id='+this.data.gs_device_id,
        })
    },
    scanQRCode:function(){

        wx.scanCode({
            success: (res) => {
              // 二维码扫描成功后的回调函数
              // 在这里可以获取到扫描到的二维码信息，例如 res.result
              // 可以进行页面跳转等操作
              wx.navigateTo({
                url: '/pages/itemInfo/itemInfo?code=' + res.result
              })
            },
            fail: (err) => {
              // 二维码扫描失败后的回调函数
            }
          })
    },
    renewalbtnOk(e){
  let id=e.currentTarget.dataset.room_id
  wx.setStorageSync('allrooms',this.data.price_list)
    wx.navigateTo({
      url: '/pages/book/book?id='+id+'&renewals=xuzu',
    })

    }

})